<template>
  <div class="book-detail-container" v-loading="loading">
    <el-card v-if="book">
      <template #header>
        <div class="card-header">
          <el-button @click="$router.back()" :icon="ArrowLeft" circle />
          <span>图书详情</span>
        </div>
      </template>

      <div class="book-detail-content">
        <div class="book-cover-large" :style="{ background: getGradientColor(book.id) }">
          <div class="cover-placeholder">
            <el-icon size="80"><Document /></el-icon>
          </div>
          <div v-if="book.isRecommended" class="recommend-badge-large">
            <el-icon><StarFilled /></el-icon>
            推荐
          </div>
        </div>

        <div class="book-info-large">
          <h1 class="book-title-large">{{ book.title }}</h1>
          <div class="book-meta-large">
            <div class="meta-item">
              <el-icon><User /></el-icon>
              <span>作者：{{ book.author }}</span>
            </div>
            <div class="meta-item" v-if="book.isbn">
              <el-icon><Document /></el-icon>
              <span>ISBN：{{ book.isbn }}</span>
            </div>
            <div class="meta-item" v-if="book.category">
              <el-icon><Folder /></el-icon>
              <span>分类：{{ book.category }}</span>
            </div>
            <div class="meta-item">
              <el-icon><Box /></el-icon>
              <span>库存：{{ book.stock }} 本</span>
            </div>
            <div class="meta-item" v-if="book.createdAt">
              <el-icon><Calendar /></el-icon>
              <span>添加时间：{{ formatDate(book.createdAt) }}</span>
            </div>
          </div>

          <div class="book-description-large" v-if="book.description">
            <h3>内容简介</h3>
            <p>{{ book.description }}</p>
          </div>

          <div class="book-actions-large">
            <el-button
              v-if="!authStore.isAdmin"
              type="primary"
              size="large"
              :disabled="book.stock <= 0"
              @click="handleBorrow"
              :icon="ShoppingCart"
            >
              借阅
            </el-button>
            <el-button
              v-if="!authStore.isAdmin"
              type="danger"
              size="large"
              :icon="isFavorite ? StarFilled : Star"
              @click="handleToggleFavorite"
            >
              {{ isFavorite ? '取消收藏' : '收藏' }}
            </el-button>
            <el-button
              v-if="!authStore.isAdmin && book.stock <= 0"
              type="warning"
              size="large"
              :icon="Clock"
              @click="handleReserve"
            >
              预约
            </el-button>
            <el-button
              v-if="authStore.isAdmin"
              type="warning"
              size="large"
              @click="handleEdit"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button
              v-if="authStore.isAdmin"
              type="danger"
              size="large"
              @click="handleDelete"
              :icon="Delete"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Document,
  User,
  Folder,
  Box,
  Calendar,
  ShoppingCart,
  Star,
  StarFilled,
  Clock,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import { bookAPI, favoriteAPI, reservationAPI, borrowAPI } from '../services/api'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const book = ref(null)
const isFavorite = ref(false)
const loading = ref(false)

const fetchBookDetail = async () => {
  loading.value = true
  try {
    const bookId = route.params.id
    const response = await bookAPI.getBookById(bookId)
    book.value = response.book
    
    // 检查是否已收藏
    if (!authStore.isAdmin) {
      try {
        const favoriteResponse = await favoriteAPI.checkFavorite(bookId)
        isFavorite.value = favoriteResponse.isFavorite || false
      } catch (error) {
        // 静默失败
      }
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取图书详情失败')
    router.back()
  } finally {
    loading.value = false
  }
}

const handleBorrow = async () => {
  try {
    await ElMessageBox.confirm(`确定要借阅《${book.value.title}》吗？`, '确认借阅', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await borrowAPI.borrowBook(book.value.id)
    ElMessage.success('借阅成功')
    await fetchBookDetail()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '借阅失败')
    }
  }
}

const handleToggleFavorite = async () => {
  try {
    if (isFavorite.value) {
      await favoriteAPI.removeFavorite(book.value.id)
      isFavorite.value = false
      ElMessage.success('取消收藏成功')
    } else {
      await favoriteAPI.addFavorite(book.value.id)
      isFavorite.value = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

const handleReserve = async () => {
  try {
    await ElMessageBox.confirm(`确定要预约《${book.value.title}》吗？`, '确认预约', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    await reservationAPI.reserveBook(book.value.id)
    ElMessage.success('预约成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '预约失败')
    }
  }
}

const handleEdit = () => {
  router.push({
    name: 'BookBorrow',
    query: { edit: book.value.id }
  })
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除《${book.value.title}》吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await bookAPI.deleteBook(book.value.id)
    ElMessage.success('删除成功')
    router.push({ name: 'BookBorrow' })
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }
}

const getGradientColor = (id) => {
  const gradients = [
    'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)'
  ]
  return gradients[id % gradients.length]
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchBookDetail()
})
</script>

<style scoped>
.book-detail-container {
  height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
}

.book-detail-content {
  display: flex;
  gap: 40px;
  padding: 20px 0;
}

.book-cover-large {
  position: relative;
  width: 300px;
  height: 400px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.cover-placeholder {
  color: rgba(255, 255, 255, 0.9);
}

.recommend-badge-large {
  position: absolute;
  top: 16px;
  left: 16px;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
  color: white;
  background: rgba(255, 193, 7, 0.9);
  display: flex;
  align-items: center;
  gap: 6px;
}

.book-info-large {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.book-title-large {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.book-meta-large {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #606266;
}

.book-description-large {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.book-description-large h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
}

.book-description-large p {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0;
}

.book-actions-large {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .book-detail-content {
    flex-direction: column;
  }

  .book-cover-large {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }

  .book-actions-large {
    justify-content: center;
  }
}
</style>

